﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using UnityEngine.Rendering;

public class TestCommandBuffer : MonoBehaviour
{
    public enum MatrixMode
    {
        Normal,
        Local2World,
        TransformVert
    }

    public RenderTexture rt;
    public Camera m_camera;
    public GameObject cube;
    public Shader cubeShader;
    public Shader sampleShader;
    private CommandBuffer cb;

    private Mesh quad;
    public MatrixMode matrixMode = MatrixMode.Normal ;
    void Start()
    {
        cb = new CommandBuffer();
        cb.name = "testCb";
        rt = new RenderTexture(m_camera.pixelWidth, m_camera.pixelHeight, 24);
        //cb.SetRenderTarget(rt);
        //cb.ClearRenderTarget(true, true, Color.black);
        MeshFilter mf = cube.GetComponent<MeshFilter>();
        Material mat = new Material(cubeShader);
        Matrix4x4 m = Matrix4x4.identity;
        if (matrixMode == MatrixMode.Local2World)
        {
            cb.SetViewProjectionMatrices(m_camera.worldToCameraMatrix, GL.GetGPUProjectionMatrix(m_camera.projectionMatrix, false));
            cb.DrawMesh(mf.mesh,cube.transform.localToWorldMatrix,mat);
        }else
        {
//        m.SetTRS(new Vector3(0, 0, 10), Quaternion.identity, Vector3.one);
//        //m.SetTRS(cube.transform.position,cube.transform.rotation,cube.transform.localScale);
            m.SetTRS(cube.transform.localPosition, Quaternion.identity, Vector3.one);
            cb.DrawMesh(mf.mesh, m, mat);
        }

        m_camera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, cb);


        quad = new Mesh();
        Vector3[] vertices = new Vector3[4];
        vertices[0] = m_camera.ScreenToWorldPoint(new Vector3(0, 0, 10));
        vertices[1] = m_camera.ScreenToWorldPoint(new Vector3(0, m_camera.pixelHeight, 10));
        vertices[2] = m_camera.ScreenToWorldPoint(new Vector3(m_camera.pixelWidth, m_camera.pixelHeight, 10));
        vertices[3] = m_camera.ScreenToWorldPoint(new Vector3(m_camera.pixelWidth, 0, 10));

        Vector2[] uvs = new Vector2[4];
        uvs[0] = new Vector2(0, 0);
        uvs[1] = new Vector2(0, 1);
        uvs[2] = new Vector2(1, 1);
        uvs[3] = new Vector2(1, 0);
        quad.vertices = vertices;
        quad.uv = uvs;

        int[] ids = new int[6];
        ids[0] = 0;
        ids[1] = 1;
        ids[2] = 2;
        ids[3] = 2;
        ids[4] = 3;
        ids[5] = 0;

        quad.triangles = ids;
        CommandBuffer cb2 = new CommandBuffer();
        cb2.name = "drawScreen";
        Material material = new Material(sampleShader);
        material.SetTexture("_MainTex", rt);
        cb2.DrawMesh(quad, Matrix4x4.identity, material);
        //camera.AddCommandBuffer(CameraEvent.AfterImageEffects, cb2);
    }
}

